package cn.service.impl;

import cn.entities.RoleMenu;
import cn.entities.UserInfo;
import cn.entities.UserRole;
import cn.mapper.UserMapper;
import cn.mapper.UserRoleMapper;
import cn.service.UserService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public UserInfo login(String username, String password) {
        Example example = new Example(UserInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("psw",password);
        UserInfo user = userMapper.selectOneByExample(example);
        return user;
    }

    @Override
    public List<UserInfo> getAllUser() {
        return userMapper.selectAll();
    }


    @Override
    public List<UserRole> getAllUserRole() {
        return userRoleMapper.selectAll();
    }

    @Override
    public void addUserInfo(UserInfo userInfo) {
        userMapper.insert(userInfo);
        String auths = userInfo.getAuths();
        if(auths !=null){
            String[]  arrAuths = auths.split(",");
            for(String mid:arrAuths){
                UserRole userRole = new UserRole(null, userInfo.getId(), Integer.parseInt(mid));
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    public UserInfo getUserById(Integer id) {
        UserInfo userInfo = userMapper.selectByPrimaryKey(id);
        List<UserRole> userRoleList = userRoleMapper.select(new UserRole(null, id, null));
        String str = "";
        for (UserRole ur:userRoleList){
            str=ur.getRoleId()+",";
        }
        userInfo.setAuths(str.substring(0,str.length()-1));
        return userInfo;
    }

    @Override
    public void deletUser(String ids) {
        String [] idsArr = ids.split(",");
        for(String id:idsArr){
            userMapper.deleteByPrimaryKey(id);
        }
    }
}
